package com.course.controller;

import com.course.model.CourseVieData;
import com.course.service.CourseVieDataService;
import com.course.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ConcurrentModel;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("course")
public class CourseController {
    @Autowired
    CourseVieDataService courseVieDataService;
    @Autowired
    RedisService redisService;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping(value = "/toViePage", produces = "text/html")
    @ResponseBody
    public String toVieCoursePage(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String html = (String) redisService.getVal("viePage");
        if (!StringUtils.isEmpty(html)){
            return html;
        }
        List<CourseVieData> list = courseVieDataService.findVieCourseData(System.currentTimeMillis());
        Model model = new ConcurrentModel();
        model.addAttribute("courseList",list);
        //手动渲染      SpringWebContext在5中过时了，官方剔除了ApplicationContext 过多的依赖，现在thymeleaf渲染不再过多依赖spring容器
        /*SpringWebContext ctx = new SpringWebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap(), applicationContext);*/
        IWebContext ctx =new WebContext(request,response,
                request.getServletContext(),request.getLocale(),model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("vie_course_page", ctx);
        if (!StringUtils.isEmpty(html)){
            redisService.setVal("viePage",html);
            return html;
        } else{
            return null;
        }

    }


}
